//
//  LXRAddTagViewController.m
//  01- 百思不得姐
//
//  Created by mac on 16/7/2.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "LXRAddTagViewController.h"
#import "LXRTagButton.h"
#import "LXRTagTextField.h"
#import "MBProgressHUD+MJ.h"
#import "SVProgressHUD.h"

@interface LXRAddTagViewController ()<UITextFieldDelegate>
/** 内容 */
@property(nonatomic,weak)UIView* contentView;
/** 文本输入框 */
@property(nonatomic,weak)LXRTagTextField* textfield;
/** 添加按钮 */
@property(nonatomic,weak)UIButton* addButton;
/** 存放标签按钮的数据 */
@property(nonatomic,strong)NSMutableArray* TagButtons;
@end

@implementation LXRAddTagViewController
#pragma mark - 懒加载
-(NSMutableArray *)TagButtons{
    
    if (_TagButtons == nil) {
        _TagButtons = [NSMutableArray new];
    }
    return _TagButtons;
}
-(UIButton *)addButton{
    
    if (_addButton == nil) {
        UIButton* addButton = [UIButton buttonWithType:UIButtonTypeCustom];
        //按钮文字和图片都左对齐 !!!
        addButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        addButton.titleLabel.font = LXRTagFont;
        
        //frame
        addButton.height = 35;
        addButton.y = CGRectGetMaxY(self.textfield.frame);
        
        //按钮内边距
        addButton.contentEdgeInsets = UIEdgeInsetsMake(0, LXRTagMargin, 0, LXRTagMargin);
        
        addButton.backgroundColor = LXRTagBg;
        [addButton addTarget:self action:@selector(addButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:addButton];
        _addButton = addButton;
    }
    return _addButton;
}
/**容器View**/
-(UIView *)contentView{
    
    if (_contentView == nil) {
        UIView* contentView = [[UIView alloc]init];
        [self.view addSubview:contentView];
        self.contentView = contentView;
    }
    return _contentView;
}
/** TextFiled设置 */
-(LXRTagTextField *)textfield{
    
    if (_textfield == nil) {

        __weak typeof(self) weakSelf = self;
        LXRTagTextField *textField = [[LXRTagTextField alloc] init];
        textField.deleteBlock = ^{
            if (weakSelf.textfield.hasText) return;
            
            [weakSelf TagButtonClick:[weakSelf.TagButtons lastObject]];
        };
        textField.delegate = self;
        [textField addTarget:self action:@selector(textDidChange) forControlEvents:UIControlEventEditingChanged];
        [textField becomeFirstResponder];
        [self.contentView addSubview:textField];
        self.textfield = textField;
        
        //LXRTagTextField继承UIControl  可以addTarget
        [self.textfield addTarget:self action:@selector(textDidChange) forControlEvents:UIControlEventEditingChanged];
        //弹出键盘
        [self.textfield becomeFirstResponder];
    }
    return _textfield;
}



#pragma mark - 初始化设置
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNav];
    

}
/** 初始化导航栏 */
-(void)setupNav{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"添加标签";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(done)];
}

/** 创建标签按钮*/
-(void)setupTagLable{
    //如果有标签
    if (self.tags.count) {
        for (NSString* tag in self.tags) {
            self.textfield.text = tag;
            [self addButtonClick];
        }
        //清空tags标签
        self.tags = nil;
    }
    
}

/** 点击完成按钮执行 */
-(void)done{
    //传递数据给上一个控制器
//    NSMutableArray* tags = [NSMutableArray new];
//    for (UIButton* tagButton in self.TagButtons) {
//        [tags addObject:tagButton.currentTitle];
//    }
    
    //传递tags给这个Block
    NSArray* tags = [self.TagButtons valueForKeyPath:@"currentTitle"];
    !self.tagsBlock ? :_tagsBlock(tags);
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 文字改变调用
-(void)textDidChange{
    //更新文本框的Frame
    [self updataTextFieldFrame];
    
    if (self.textfield.hasText) {//有文字
        //显示添加标签按钮
        self.addButton.hidden = NO;
        self.addButton.y = CGRectGetMaxY(self.textfield.frame) + LXRTagMargin;
        //文字
        NSString* title = [NSString stringWithFormat:@"添加标签:%@",self.textfield.text];
        [self.addButton setTitle:title forState:UIControlStateNormal];
        
        //获得最后一个字符
        NSString* text = self.textfield.text;
        NSInteger len = text.length;
        NSString* lastLetter = [text substringFromIndex:len - 1];
        if ([lastLetter isEqualToString:@","] || [lastLetter isEqualToString:@"，"]) {
            //去除逗号
            self.textfield.text = [text substringToIndex:len - 1];
            [self addButtonClick];
        }
    }else{  //没有文字
        //隐藏添加标签按钮
        self.addButton.hidden = YES;
    }
}

#pragma mark - 监听按钮点击
/** 监听加号按钮点击 */
-(void)addButtonClick{
    //判断最多5个标签
    if (self.TagButtons.count == 5) {
        [MBProgressHUD showError:@"最多添加5个标签"];
//        [SVProgressHUD showErrorWithStatus:@"最多添加5个标签"];
//        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        return;
    }
    
    //添加一个"标签按钮"
    LXRTagButton* tagButton = [LXRTagButton buttonWithType:UIButtonTypeCustom];
    [tagButton setTitle:self.textfield.text forState:UIControlStateNormal];
    [tagButton addTarget:self action:@selector(TagButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    //添加到父控件
    [self.contentView addSubview:tagButton];
    //添加到数组
    [self.TagButtons addObject:tagButton];
    //清空textField文字
    self.textfield.text = nil;
    self.addButton.hidden = YES;
    
    //更新 标签按钮和文本框 的frame
    [self updateTagButtonFrame];
    [self updataTextFieldFrame];
    
    
}
/** 点击标签按钮 */
-(void)TagButtonClick:(UIButton*)tagButton{
    //从父控件删除
    [tagButton removeFromSuperview];
    //从数组中删除
    [self.TagButtons removeObject:tagButton];
    //重新更新标签按钮的Frame
    [UIView animateWithDuration:0.25 animations:^{
        //更新 标签按钮和文本框 的frame
        [self updateTagButtonFrame];
        [self updataTextFieldFrame];
    }];
    
}



#pragma mark - ViewDidLayoutSubviews
/** 布局控制器View的子控件*/
-(void)viewDidLayoutSubviews{
    
    [super viewDidLayoutSubviews];
    //contentView的Frame
    self.contentView.x = LXRTagMargin;
    self.contentView.y = 64 + LXRTagMargin;
    self.contentView.width = self.view.width - self.contentView.x;
    self.contentView.height = LXRScreenH;
    
    //TextFiled的Frame
    self.textfield.width = self.contentView.width;
    
    //addButton的Frame
    self.addButton.width = self.contentView.width;
    
    //创建标签Lable
    [self setupTagLable];
    
}

#pragma mark - 计算Frame
/** 更新标签按钮的Frame */
-(void)updateTagButtonFrame{
    
    //更新标签按钮的Frame
    for (int i = 0; i<self.TagButtons.count; i++) {
        LXRTagButton* tagButton = self.TagButtons[i];
        //最前面的标签按钮
        if (i == 0) {
            tagButton.x = 0;
            tagButton.y = 0;
        }else{ //其他标签按钮
            LXRTagButton* lastTagButton = self.TagButtons[i - 1];
            //当前行左边的间距
            CGFloat leftWidth = CGRectGetMaxX(lastTagButton.frame) + LXRTagMargin;
            //当前行右边的间距
            CGFloat rightWidth = self.contentView.width - leftWidth;
            if (rightWidth >= tagButton.width) { //按钮显示在当前行
                tagButton.x = leftWidth;
                tagButton.y = lastTagButton.y;
            }else{//显示在下一行
                tagButton.x = 0;
                tagButton.y = CGRectGetMaxY(lastTagButton.frame) + LXRTagMargin;
            }
            
        }
    }
    
    // 更新“添加标签”的frame
    self.addButton.y = CGRectGetMaxY(self.textfield.frame) + LXRTagMargin;
    
    
}
/** 更新文本框的Frame*/
-(void)updataTextFieldFrame{
    //最后一个标签按钮
    LXRTagButton* lastTagButton = [self.TagButtons lastObject];
    CGFloat leftWidth = CGRectGetMaxX(lastTagButton.frame) + LXRTagMargin;
    
    if (self.contentView.width - leftWidth >= [self textFieldTextWidth]) {
        self.textfield.x = leftWidth;
        self.textfield.y = lastTagButton.y;
    }else{
        self.textfield.x = 0;
        self.textfield.y = CGRectGetMaxY(lastTagButton.frame) + LXRTagMargin;
    }
}
/** textField文字宽度 */
-(CGFloat)textFieldTextWidth{
    CGFloat textW =  [self.textfield.text sizeWithAttributes:@{NSFontAttributeName : self.textfield.font}].width;
    //如果有100距离不换行,如果不够就按文字的宽度
    return MAX(100, textW);
}

#pragma mark - <LXRTagTextFieldDelegate>
/**
 *  监听键盘最右下角按钮的点击(return key  比如"换行","完成")
 */
-(BOOL)textFieldShouldReturn:(LXRTagTextField *)textField{
    if ([textField hasText]) {
        [self addButtonClick];
    }
    return YES;
}


@end
